/*
 * Copyright 2011 Jeff Larsen
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.resources.rg;

import com.google.gwt.dev.util.TextOutput;
import com.google.gwt.resources.css.CssGenerationVisitor;
import com.google.gwt.resources.css.ast.Context;
import com.google.gwt.resources.css.ast.CssProperty;
import com.google.gwt.resources.css.ast.CssProperty.IdentValue;
import com.google.gwt.resources.css.ast.CssProperty.StringValue;
import com.google.gwt.resources.css.ast.CssProperty.Value;
import com.google.gwt.resources.css.ast.CssRule;

import java.util.List;

public class Css3PieGenerationVisitor extends CssGenerationVisitor {
  
  private boolean ruleHasPie = false;
  private CssProperty prop = null;
  private final CssProperty pie ;

  public Css3PieGenerationVisitor(TextOutput out) {
    super(out);
    IdentValue value = new IdentValue("url('PIE.htc');");
    pie = new CssProperty("behavior", value,false);
  }

  @Override
  public void endVisit(CssRule x, Context ctx) {
    
    if(prop != null){
      prop.traverse(this, ctx);
    }
    
    if(ruleHasPie){
      pie.traverse(this, ctx);
    }
    super.endVisit(x, ctx);
    ruleHasPie=false;
    prop = null;
  }

  @Override
  public boolean visit(CssProperty x, Context ctx) {
    if(x.getName().trim().equalsIgnoreCase("border-radius")){
      ruleHasPie=true;
    }else if(x.getName().trim().equalsIgnoreCase("box-shadow")){
      ruleHasPie=true;
    }else if(x.getName().trim().equalsIgnoreCase("border-image")){
      ruleHasPie=true;
    }else if(x.getName().trim().equalsIgnoreCase("background")){
      List<Value> values = x.getValues().getValues();
      for(Value v :values){
        IdentValue identValue = v.isIdentValue();
        if(identValue != null){
          if(identValue.getExpression().startsWith("\"linear-gradient")){
            prop = new CssProperty("-pie-background", x.getValues(), false);
            ruleHasPie=true;
          }
        }
      }
    }
    return super.visit(x, ctx);
  }
  
}
